package com.zcxy.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxy.constant.CommonConstant;
import com.zcxy.core.bean.PageQuery;

import com.zcxy.mybatis.service.BaseServiceImpl;
import com.zcxy.mybatis.util.RelationHelper;
import com.zcxy.sys.constant.Constant;
import com.zcxy.sys.entity.SysDict;
import com.zcxy.sys.entity.SysDictItem;
import com.zcxy.sys.mapper.SysDictMapper;
import com.zcxy.sys.pojo.SysDictVo;
import com.zcxy.sys.service.ISysDictItemService;
import com.zcxy.sys.service.ISysDictService;
import com.zcxy.util.Assert;
import com.zcxy.util.BeanCopierUtil;

import com.zcxy.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典主表Service业务层处理
 *
 * @author zcc
 * @email 860474958@qq.com
 * @date 2020-06-04
 */
@Service
@Slf4j
public class SysDictServiceImpl extends BaseServiceImpl<SysDictMapper, SysDict>
        implements ISysDictService {
    @Autowired
    private ISysDictService iSysDictService;

    @Autowired
    private ISysDictItemService iSysDictItemService;

    @Autowired
    private SysDictMapper sysDictMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IPage<SysDictVo> queryPageList(PageQuery<SysDict> queryVo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        Page page = new Page(queryVo.getPageNo(), queryVo.getPageSize());
        if (queryVo.getT() != null && !StringUtils.isEmpty(queryVo.getT().getName())) {
            queryWrapper.like("name", queryVo.getT().getName());
        }

        if (queryVo.getT() != null && !StringUtils.isEmpty(queryVo.getT().getStatus())) {
            queryWrapper.eq("status", queryVo.getT().getStatus());
        }

        queryWrapper.orderByDesc("create_time");
        IPage<SysDict> sysUserVoIPage = baseMapper.selectPage(page, queryWrapper);

        IPage<SysDictVo> sysDictVoList = BeanCopierUtil.copyPage(sysUserVoIPage, SysDictVo.class);
        if (null != sysDictVoList.getRecords()) {
            sysDictVoList.getRecords().stream().forEach(t -> {
                List<SysDictItem> items = iSysDictItemService.viewSysDictItemsById(t.getId());
                if (!items.isEmpty()) {
                    t.setHasItem(1);
                } else {
                    t.setHasItem(0);
                }
            });
        }
        return sysDictVoList;
    }

    @Override
    public List<SysDictVo> queryList(SysDict sysDict) {
        sysDict = sysDict == null ? new SysDict() : sysDict;
        if (StringUtils.isEmpty(sysDict.getStatus())) {
            sysDict.setStatus(Constant.ENABLE);
        }
        return BeanCopierUtil.copyListToList(baseMapper.selectList(new QueryWrapper<>(sysDict)), SysDictVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysDict addSysDict(SysDict queryVo) {
        String maxcode = sysDictMapper.selectmaxcode();
        if(maxcode==null|| com.zcxy.util.StringUtils.isEmpty(maxcode))
         {
            queryVo.setCode("10000001");
             maxcode="10000001";
        }

        int i = Integer.valueOf(maxcode) + 1;
        String max = String.valueOf(i);
        queryVo.setCode(max);
        validFiledExistInsert("name", queryVo.getName(), "添加名称不可重复");
        queryVo.setDelFlag(CommonConstant.DEL_FLAG_1);
        //TODO 具体新增业务限制各自实现
        baseMapper.insert(queryVo);
        return queryVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysDict(SysDict queryVo) {
        validFiledExistUpdate("name", queryVo.getName(), "id", queryVo.getId(), "名称不可重复");
        SysDict sysDictDb = baseMapper.selectById(queryVo.getId());
        BeanCopierUtil.copyObject(queryVo, sysDictDb);
        baseMapper.updateById(sysDictDb);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDisable(List<String> ids) {
        updateSysStatus(Constant.DISABLE, ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEnable(List<String> ids) {
        updateSysStatus(Constant.ENABLE, ids);
    }

    public void updateSysStatus(String status, List<String> ids) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id", ids);
        List<SysDict> sysDict = baseMapper.selectList(queryWrapper);
        sysDict.stream().forEach(i -> {
            i.setStatus(status);
        });
        saveOrUpdateBatch(sysDict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> removeAllSysDict(List<String> ids) {
        List<String> names = new ArrayList();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.in("id", ids);
        sysDictMapper.delete(queryWrapper);

        return names;
    }

    @Override
    public SysDictVo viewSysDict(String id) {
        SysDict sysDict = iSysDictService.getBaseMapper().selectById(id);
        SysDictVo sysDictVo = BeanCopierUtil.copyObject(sysDict, SysDictVo.class);
        RelationHelper.render(sysDictVo);
        return sysDictVo;
    }

    @Override
    public List<SysDictItem> queryListSelectDataByCode(String code) {
        SysDict sysDictq = new SysDict();
        sysDictq.setCode(code);
        SysDict sysDict = baseMapper.selectOne(new QueryWrapper<>(sysDictq));
        Assert.notNull(sysDict, "传入字典code无法查询到对应的列表值");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status", Constant.ENABLE);
        queryWrapper.eq("dict_id", sysDict.getId());
        List<SysDictItem> sysDictItems = iSysDictItemService.getBaseMapper().selectList(queryWrapper);
        return sysDictItems;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void download(SysDict queryVo, HttpServletResponse response) throws IOException {
        List<SysDict> sysDicts = baseMapper.selectList(new QueryWrapper<>(queryVo));
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysDict sysDictExcel : sysDicts) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("主键", sysDictExcel.getId());
            map.put("列表代码", sysDictExcel.getCode());
            map.put("列表名称", sysDictExcel.getName());
            map.put("描述", sysDictExcel.getRemark());
            map.put("0禁用1启用", sysDictExcel.getStatus());
            map.put("排序", sysDictExcel.getSort());
            map.put("0-可删除1不可删除系统默认", sysDictExcel.getCanDel());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

}
